<!--
 * @Author: 黄达全
 * @Date: 2024-08-21 19:56:45
 * @LastEditTime: 2024-08-21 20:56:22
-->
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue"
import categoryApi from "@/api/model/category"
import managerApi from "@/api/model/manager"
import type { CategoryTreeVO } from "@/common/type"

const filterFormRef = ref<HTMLDivElement | null>()

// 表单数据
const initForm = reactive({
    name: "",
    category: "", // 存储最终选中的分类ID
    create_manager: "", // 存储选中的管理员ID
})

// 分类数据
const categoryOptions = ref<CategoryTreeVO[]>([])
const categoryProps = {
    value: 'id',
    label: 'name',
    children: 'children',
    checkStrictly: true, // 可以选择任意一级
    emitPath: false // 只返回选中节点的值，而不是路径数组
}

// 管理员数据
const managerOptions = ref<{id: number, username: string}[]>([])
const managerLoading = ref(false)

// 加载根分类数据
const loadRootCategories = async () => {
    try {
        const res = await categoryApi.tree()
        if(res.code === 1 && res.data) {
            categoryOptions.value = res.data
        }
    } catch (error) {
        console.error("加载分类数据失败:", error)
    }
}

// 加载管理员数据
const loadManagers = async () => {
    managerLoading.value = true
    try {
        const res = await managerApi.selectXiaLa()
        if(res.code === 1 && res.data) {
            managerOptions.value = res.data
        }
    } catch (error) {
        console.error("加载管理员数据失败:", error)
    } finally {
        managerLoading.value = false
    }
}

// 在组件加载时获取初始数据
onMounted(() => {
    loadRootCategories()
    loadManagers()
})

// 级联选择器异步加载子分类
const loadCategoryChildren = async (node: any, resolve: (data: CategoryTreeVO[]) => void) => {
    if (node.level === 0) {
        // 根级别，直接返回已加载的数据
        return resolve(categoryOptions.value)
    }
    
    // 加载子分类
    const parentId = node.data.id
    try {
        const res = await categoryApi.select(parentId, 1) // 假设第一页包含所有子分类
        if(res.code === 1 && res.data && res.data.records) {
            resolve(res.data.records)
        } else {
            resolve([])
        }
    } catch (error) {
        console.error("加载子分类失败:", error)
        resolve([])
    }
}

// 定义事件
const emit = defineEmits(['search', 'reset'])

// 搜索方法
const handleSearch = () => {
    // 向父组件传递搜索条件
    emit('search', { ...initForm })
}

// 重置方法
const handleReset = () => {
    // 重置表单数据
    initForm.name = ""
    initForm.category = ""
    initForm.create_manager = ""
    
    // 通知父组件已重置
    emit('reset')
}
</script>

<template>
    <div class="filterForm" ref="filterFormRef">
        <div class="container_left">
            <el-form inline label-width="90" :model="initForm">
                <el-form-item label="商品名称：">
                    <el-input :style="{width: '150px'}" size="small" v-model="initForm.name" placeholder="请输入商品名称" clearable @keyup.enter="handleSearch" />
                </el-form-item>
                <el-form-item label="商品分类：">
                    <el-cascader
                        v-model="initForm.category"
                        :options="categoryOptions"
                        :props="categoryProps"
                        :load="loadCategoryChildren"
                        size="small"
                        placeholder="请选择商品分类"
                        clearable
                        style="width: 220px;"
                    />
                </el-form-item>
                <el-form-item label="创建人：">
                    <el-select
                        v-model="initForm.create_manager"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择创建人"
                        :loading="managerLoading"
                        size="small"
                        style="width: 180px;"
                        clearable
                    >
                        <el-option
                            v-for="item in managerOptions"
                            :key="item.id"
                            :label="item.username"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" @click="handleSearch" style="background-color: var(--primary-theme-color) ;">
                        <el-icon class="el-icon--left" ><el-icon-search /></el-icon>
                        搜索
                    </el-button>
                    <el-button size="small" @click="handleReset">
                        <el-icon class="el-icon--left"><el-icon-refresh-right /></el-icon>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.filterForm {
    width: 100%;
    min-height: 60px;
    transition: 0.4s;
    display: flex;
    border-bottom: 1px dotted #DCDFE6;
    padding: 5px 0;
    
    .container_left {
        flex: 1;
        display: flex;
        padding-top: 10px;
        
        :deep(.el-form) {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
        }
        
        :deep(.el-form-item) {
            margin-bottom: 10px;
            margin-right: 15px;
        }
        
        :deep(.el-form-item:last-child) {
            margin-right: 0;
        }
    }
}
</style>
